package com.fingard.dsp.bank.helpers.receipthelpers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;

import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.text.StringHelper;
import com.fingard.util.ZipHelper;

/**回单文件下载，ftp/sftp、银行前置目录等方式，
 * 发现文件下载比较通用，故新建此类，用于公共调用*/
public class DownReceiptFileHelper {

	private DirectBase directBase;
	private String downType;
	public DownReceiptFileHelper(DirectBase pDirectBase){
		directBase = pDirectBase;
		downType = directBase.getBankConfig().getValueAsString("receiptRequestType");
    	String downType2 = directBase.bankFront.getStrValueByFor("receiptDownloadType", "");
    	if(StringHelper.hasAnyChar(downType2)){
    		downType = downType2;//前置机的配置覆盖config
    	}
    	directBase.WriteBankLogLn("downType:"+downType);
	}
	
	/**取得包括特定字符（一般是日期）的文件（一般是zip文件）*/
	private ArrayList<String> getFilesLoop(File pDir, String pChkNameSubStr, String pExt){
		ArrayList<String> retList = new ArrayList<String>();
		File[] subFiles = pDir.listFiles();
		if(subFiles !=null && subFiles.length>0){
			String cmpStr = pChkNameSubStr.toLowerCase();
			String cmpExt = "";
			if(StringHelper.hasAnyChar(pExt)){
				cmpExt = "." + pExt.toLowerCase();
			}
			for(File eachFile : subFiles){
				if(eachFile.isDirectory()){
					ArrayList<String> subList = getFilesLoop(eachFile, pChkNameSubStr, pExt);
					if(subList!=null && subList.size()>0){
						retList.addAll(subList);
					}
				}
				String nameForChk = eachFile.getName().toLowerCase();
				if(nameForChk.contains(cmpStr) && (cmpExt.length()==0 || nameForChk.endsWith(cmpExt))){
					retList.add(eachFile.getAbsolutePath());
				}
			}
		}
		return retList;
	}
	
	/**下载符合条件的zip文件，并解压*/
	public ArrayList<String> downAndUnZipFiles(String pDestDir, String pChkNameSubStr){
		MixFtp mixFtp = null;
		ArrayList<String> trgFiles = new ArrayList<String>();
		try{
			//解压临时目录
			FileHelper.mkdirsIfNotExists(pDestDir);
			if("localhost".equalsIgnoreCase(downType)){//本地目录
				File mainDir = new File(directBase.bankFront.bankReceiptMainDir);
				trgFiles = getFilesLoop(mainDir, pChkNameSubStr, "zip");
			}else{
				FtpSet ftpSet = directBase.bankFront.getFtpSet("receipt");
				directBase.WriteBankLogLn("ftpType："+ftpSet.ftpType+"，服务地址："+ftpSet.serverIP+":"+ftpSet.port);
				mixFtp = new MixFtp(ftpSet);
				ArrayList<String> fileNameList = mixFtp.listNames(ftpSet.downDir);
				if(fileNameList == null || fileNameList.size() == 0){
					directBase.WriteBankLogLn("目录："+ftpSet.downDir+"下，无文件");
					return trgFiles;
				}
				for(String eachName : fileNameList){
					String nameForChk = eachName.toLowerCase();
					String cmpStr = pChkNameSubStr.toLowerCase();
					if(nameForChk.contains(cmpStr) && nameForChk.endsWith(".zip")){
						directBase.WriteBankLogLn("下载"+eachName);
						String localFilePath = StringHelper.trimEndFileSp(pDestDir) + File.separator + eachName;
						FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(ftpSet.downDir, eachName, localFilePath);
						if(ftpReceiver.isCompleted){
							trgFiles.add(localFilePath);
						}else{
							directBase.WriteBankLogLn(eachName+"文件下载失败："+ftpReceiver.connMsg);
						}
					}
				}
				mixFtp.disconnect();//尽快关闭ftp连接
				mixFtp = null;
			}
			
			HashSet<String> filterFp = new HashSet<String>();
			if(trgFiles.size()>0){
				for(String eachZip : trgFiles){
					File eachZipFile = new File(eachZip);
					filterFp.add(eachZipFile.getAbsolutePath());
				}
			}
			if(trgFiles.size()>0){
				for(String eachZip : trgFiles){
					directBase.WriteBankLogLn("开始解压文件" + eachZip);
					ZipHelper.unzipFile(eachZip, pDestDir);
					File dir2 = new File(pDestDir);
					upzipFilesLoop(dir2, filterFp);
				}
			}else{
				directBase.WriteBankLogLn("无符合条件的回单压缩文件，条件：文件名含“"+pChkNameSubStr+"”的zip文件");
			}
		}catch(Exception ex){
			directBase.WriteBankLogLn(ex);
		}finally{
			if(mixFtp!=null){
				try {
					mixFtp.disconnect();
				} catch (IOException e) {
					directBase.WriteBankLogLn(e);
				}
			}
		}
		return trgFiles;
	}
	
	private void upzipFilesLoop(File pDir, HashSet<String> pFilterFp){
		File[] subFiles = pDir.listFiles();
		if(subFiles !=null && subFiles.length>0){
			String cmpExt = ".zip";
			
			for(File eachFile : subFiles){
				if(eachFile.isDirectory()){
					upzipFilesLoop(eachFile, pFilterFp);
				}
				if(pFilterFp.contains(eachFile.getAbsolutePath())){
					continue;
				}
				String nameForChk = eachFile.getName().toLowerCase();
				if(nameForChk.endsWith(cmpExt)){
					directBase.WriteBankLogLn("开始解压内层文件" + eachFile.getName());
					String nameOnly = StringHelper.splitFileNameAndExt(eachFile.getName())[0];
					ZipHelper.unzipFile(eachFile.getAbsolutePath(), eachFile.getParent()+File.separator+nameOnly);
				}
			}
		}
	}
}
